﻿$(document).ready(function() {
    var allowedAnswers = parseInt($('#allowedAnswers').val());
    var feedbackSent = false;
    $('.optionCheckBox').click(function() {
        if ($(':checkbox:checked').length > allowedAnswers) {
            return false;
        }
    });
    $('#submit').click(function() {
        if ($(':checkbox:checked').length == 0) {
            $('#respondError').text("No options have been selected");
            $('#submit').blur(function() {
                $('#respondError').text("");
                $('#submit').unbind('blur');
            });
        }
        else {
            if (!feedbackSent && $('#respondFeedbackTextArea').val().length != 0) {
                feedbackSent = true;
                $.ajax({
                    type: 'POST',
                    url: "/Respond/SaveFeedback",
                    data: { questionID: $('#questionID').val(), comment: $('#respondFeedbackTextArea').val() }
                });
            }
            $.ajax({
                type: 'POST',
                url: "/Respond/DeleteDemographicResponse",
                data: { questionID: $('#questionID').val() },
                async: false
            });
            responseSent = true;
            $('#submit').val("Sent");
            $('#submit').attr("disabled", true);
            $('.optionCheckBox').each(function() {
                $(this).click(function() {
                    $('#submit').attr("disabled", false);
                    $('#submit').val("Submit");
                    $('.optionCheckBox').each(function() {
                        $(this).unbind('click');
                        $(this).click(function() {
                            if ($(':checkbox:checked').length > allowedAnswers) {
                                return false;
                            }
                        });
                    });
                });
            });
            var i = 0;
            $(':checkbox:checked').each(function() {
                $.ajax({
                    type: 'POST',
                    url: "/Respond/SaveDemographicResponse",
                    data: { questionID: $('#questionID').val(), optionID: $(this).attr("id") },
                    success: function() {
                        i++;
                        if (i == allowedAnswers) {
                            $('#submit').val("Sent");
                            $('#submit').attr("disabled", true);
                            i = 0;
                        }
                    }
                });
            });
        }
    });
});